package cn.zlg.common.datadump.util;

import com.mysema.commons.lang.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpServletRequestWrapperWithPrefix extends HttpServletRequestWrapper {

    String prefix;
    Map<String,String[]> paramValueMap;
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public HttpServletRequestWrapperWithPrefix(HttpServletRequest request, String prefix) {
        super(request);
        Assert.notNull(prefix, "prefix不能为null");
        init(request, prefix);
    }

    void init(HttpServletRequest request, String prefix) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        paramValueMap = new HashMap<>();
        for(Map.Entry<String, String[]> e: parameterMap.entrySet()) {
            if(e.getKey().startsWith(prefix)) {
                paramValueMap.put(e.getKey().substring(prefix.length()), e.getValue());
            }
        }
    }

    @Override
    public String getParameter(String name) {
        String[] strings = paramValueMap.get(name);
        return strings == null ? null : strings[0];
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return paramValueMap;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        Iterator<String> it = paramValueMap.keySet().iterator();
        return new Enumeration<String>() {
            @Override
            public boolean hasMoreElements() {
                return it.hasNext();
            }

            @Override
            public String nextElement() {
                return it.next();
            }
        };
    }

    @Override
    public String[] getParameterValues(String name) {
        return paramValueMap.get(name);
    }
}
